﻿#include "ITask.h"

ITask::ITask(QObject *parent)
    : QObject{parent}
    , m_running(QAtomicInteger<bool>(false))
{
    // 将任务对象绑定到独立线程
    this->moveToThread(&m_taskThread);

    // 当线程启动时，执行 run()
    connect(&m_taskThread, &QThread::started, this, &ITask::run);

    // 线程结束时自动发 finished 信号
    connect(&m_taskThread, &QThread::finished, this, [this]() {
        if (m_running) {
            // 正常执行完
            m_running = false;
            emit taskFinished();
        } else {
            // 强制终止
            emit taskStopped();
        }
    });
}

ITask::~ITask()
{
    stop();
    m_taskThread.quit();
    m_taskThread.wait();
}

void ITask::setTaskName(const QString &name)
{
    m_taskName = name;
}

QString ITask::taskName() const
{
    return m_taskName;
}

bool ITask::isRunning() const
{
    return m_running.loadRelaxed();
}

void ITask::start()
{
    if (m_running) {
        return;
    }
    m_running = true;
    m_taskThread.start();
}

void ITask::stop()
{
    if (!m_taskThread.isRunning()) return;

    m_taskThread.terminate(); // 强制终止

    m_running = false;
}

QString ITask::INFO_TASK_STOPPED(const QString &taskname)
{
    return tr("Task [ %1 ] stopped.").arg(taskname);
}

QString ITask::WARN_TASK_IS_RUNNING(const QString &taskname)
{
    return tr("Task [ %1 ] is running, stop it please!").arg(taskname);
}

void ITask::moveThread(QObject *obj)
{
    if (!obj) this->moveToThread(&m_taskThread);
    else obj->moveToThread(&m_taskThread);
}

void ITask::run()
{
    emit taskStarted();

    if (m_running) {
        runTask();
    }

    // runTask 完成后，退出线程
    m_taskThread.quit();
}
